import React, { useState, useEffect } from 'react';
import {
  Card,
  Row,
  Col,
  DatePicker,
  Select,
  Table,
  Tag,
  Button,
  Space,
  Statistic,
  Input,
  Tooltip,
  Empty,
  Spin,
} from 'antd';
import {
  LineChart,
  Line,
  BarChart,
  Bar,
  PieChart,
  Pie,
  AreaChart,
  Area,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip as RechartsTooltip,
  Legend,
  ResponsiveContainer,
  Cell,
} from 'recharts';
import { SearchOutlined, ReloadOutlined, FilterOutlined, DownloadOutlined } from '@ant-design/icons';
import { getApiStatistics, getApiMonitorData, getApiPerformance, exportMonitorData } from '../../services/api.jsx';
import './MonitorDashboard.css';

const { RangePicker } = DatePicker;
const { Option } = Select;
const { Search } = Input;

const MonitorDashboard = () => {
  // State management
  const [loading, setLoading] = useState(false);
  const [dateRange, setDateRange] = useState([]);
  const [apiFilter, setApiFilter] = useState('');
  const [statusFilter, setStatusFilter] = useState('');
  const [statistics, setStatistics] = useState({
    totalRequests: 0,
    avgResponseTime: 0,
    errorRate: 0,
    successRate: 0,
  });
  const [performanceData, setPerformanceData] = useState([]);
  const [errorTrendData, setErrorTrendData] = useState([]);
  const [trafficDistributionData, setTrafficDistributionData] = useState([]);
  const [apiMonitorList, setApiMonitorList] = useState([]);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });

  // Fetch data
  const fetchData = async (params = {}) => {
    setLoading(true);
    try {
      // Get statistics
      const statsRes = await getApiStatistics(dateRange);
      if (statsRes.success) {
        setStatistics(statsRes.data);
      }

      // Get performance data
      const perfRes = await getApiPerformance(dateRange);
      if (perfRes.success) {
        setPerformanceData(perfRes.data);
      }

      // Get error trend data
      const errorRes = await getApiStatistics(dateRange, { type: 'error' });
      if (errorRes.success) {
        setErrorTrendData(errorRes.data);
      }

      // Get traffic distribution data
      const trafficRes = await getApiStatistics(dateRange, { type: 'traffic' });
      if (trafficRes.success) {
        setTrafficDistributionData(trafficRes.data);
      }

      // Get API monitor list
      const monitorParams = {
        ...params,
        apiName: apiFilter,
        status: statusFilter,
        dateRange,
      };
      const monitorRes = await getApiMonitorData(monitorParams);
      if (monitorRes.success) {
        setApiMonitorList(monitorRes.data.items);
        setPagination({
          ...pagination,
          total: monitorRes.data.total,
          current: params.current || 1,
        });
      }
    } catch (error) {
      console.error('Failed to fetch monitor data:', error);
    } finally {
      setLoading(false);
    }
  };

  // Initial data fetch
  useEffect(() => {
    // Set default date range to last 7 days
    const end = new Date();
    const start = new Date();
    start.setDate(start.getDate() - 7);
    setDateRange([start, end]);
    fetchData();
  }, []);

  // Refresh data when filters change
  useEffect(() => {
    if (dateRange.length > 0) {
      fetchData();
    }
  }, [dateRange, apiFilter, statusFilter]);

  // Handle page change
  const handlePageChange = (page, pageSize) => {
    setPagination({ ...pagination, current: page, pageSize });
    fetchData({ current: page, pageSize });
  };

  // Handle export data
  const handleExport = async () => {
    try {
      const exportParams = {
        apiName: apiFilter,
        status: statusFilter,
        dateRange,
      };
      const res = await exportMonitorData(exportParams);
      if (res.success) {
        // Create download link
        const url = window.URL.createObjectURL(new Blob([res.data]));
        const link = document.createElement('a');
        link.href = url;
        link.setAttribute('download', `api-monitor-data-${new Date().toISOString().split('T')[0]}.csv`);
        document.body.appendChild(link);
        link.click();
        link.remove();
      }
    } catch (error) {
      console.error('Failed to export data:', error);
    }
  };

  // Columns for API monitor table
  const monitorColumns = [
    {
      title: 'API名称',
      dataIndex: 'apiName',
      key: 'apiName',
      ellipsis: true,
      render: (text) => (
        <Tooltip title={text}>
          <span>{text}</span>
        </Tooltip>
      ),
    },
    {
      title: '请求时间',
      dataIndex: 'requestTime',
      key: 'requestTime',
      sorter: (a, b) => new Date(a.requestTime) - new Date(b.requestTime),
    },
    {
      title: '响应时间(ms)',
      dataIndex: 'responseTime',
      key: 'responseTime',
      sorter: (a, b) => a.responseTime - b.responseTime,
      render: (time) => (
        <span className={time > 500 ? 'response-time-slow' : ''}>{time}</span>
      ),
    },
    {
      title: '状态码',
      dataIndex: 'statusCode',
      key: 'statusCode',
      render: (code) => {
        let color = 'green';
        if (code >= 500) color = 'red';
        else if (code >= 400) color = 'orange';
        else if (code >= 300) color = 'blue';
        return (
          <Tag color={color}>{code}</Tag>
        );
      },
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status) => (
        <Tag color={status === 'success' ? 'green' : 'red'}>
          {status === 'success' ? '成功' : '失败'}
        </Tag>
      ),
    },
    {
      title: 'IP地址',
      dataIndex: 'ipAddress',
      key: 'ipAddress',
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <Button type="text" size="small">详情</Button>
          <Button type="text" size="small">重试</Button>
        </Space>
      ),
    },
  ];

  // Colors for charts
  const COLORS = ['#0088FE', '#00C49F', '#FFBB28', '#FF8042', '#8884d8', '#82ca9d'];

  return (
    <div className="monitor-dashboard">
      {/* Header */}
      <div className="dashboard-header">
        <h1>API监控中心</h1>
      </div>

      {/* Filter Section */}
      <Card className="filter-section">
        <Row gutter={[16, 16]}>
          <Col xs={24} sm={24} md={12} lg={12} xl={8}>
            <RangePicker
              value={dateRange}
              onChange={(dates) => setDateRange(dates || [])}
              className="w-full"
            />
          </Col>
          <Col xs={24} sm={24} md={12} lg={12} xl={8}>
            <Search
              placeholder="搜索API名称"
              value={apiFilter}
              onChange={(e) => setApiFilter(e.target.value)}
              onSearch={() => fetchData()}
              allowClear
              enterButton={<SearchOutlined />}
              className="w-full"
            />
          </Col>
          <Col xs={24} sm={24} md={12} lg={12} xl={8}>
            <Space className="w-full">
              <Select
                placeholder="选择状态"
                value={statusFilter}
                onChange={(value) => setStatusFilter(value)}
                allowClear
                className="w-full"
              >
                <Option value="success">成功</Option>
                <Option value="error">失败</Option>
              </Select>
              <Button 
                icon={<ReloadOutlined />} 
                onClick={() => fetchData()} 
                loading={loading}
              >
                刷新
              </Button>
            </Space>
          </Col>
        </Row>
      </Card>

      {/* Statistics Cards */}
      <Row gutter={[16, 16]} className="mb-4">
        <Col xs={24} sm={12} md={6}>
          <Card className="stat-card">
            <Statistic
              title="总请求数"
              value={statistics.totalRequests}
              valueStyle={{ color: '#3f8600' }}
              suffix="次"
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} md={6}>
          <Card className="stat-card">
            <Statistic
              title="平均响应时间"
              value={statistics.avgResponseTime}
              valueStyle={{ color: '#cf1322' }}
              suffix="ms"
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} md={6}>
          <Card className="stat-card">
            <Statistic
              title="错误率"
              value={statistics.errorRate}
              valueStyle={{ color: '#d46b08' }}
              suffix="%"
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} md={6}>
          <Card className="stat-card">
            <Statistic
              title="成功率"
              value={statistics.successRate}
              valueStyle={{ color: '#1890ff' }}
              suffix="%"
            />
          </Card>
        </Col>
      </Row>

      {/* Charts Section */}
      <Row gutter={[16, 16]} className="mb-4">
        <Col xs={24} md={12}>
          <Card title="API性能趋势" className="chart-card">
            <ResponsiveContainer width="100%" height={300}>
              <LineChart data={performanceData}>
                <CartesianGrid strokeDasharray="3 3" />
                <XAxis dataKey="date" />
                <YAxis />
                <RechartsTooltip />
                <Legend />
                <Line type="monotone" dataKey="responseTime" stroke="#8884d8" name="响应时间(ms)" />
                <Line type="monotone" dataKey="successRate" stroke="#82ca9d" name="成功率(%)" />
              </LineChart>
            </ResponsiveContainer>
          </Card>
        </Col>
        <Col xs={24} md={12}>
          <Card title="错误趋势" className="chart-card">
            <ResponsiveContainer width="100%" height={300}>
              <AreaChart data={errorTrendData}>
                <CartesianGrid strokeDasharray="3 3" />
                <XAxis dataKey="date" />
                <YAxis />
                <RechartsTooltip />
                <Legend />
                <Area type="monotone" dataKey="errorCount" stroke="#ff7300" fill="#ff7300" fillOpacity={0.3} name="错误数" />
              </AreaChart>
            </ResponsiveContainer>
          </Card>
        </Col>
      </Row>

      <Row gutter={[16, 16]} className="mb-4">
        <Col xs={24} md={12}>
          <Card title="流量分布" className="chart-card">
            <ResponsiveContainer width="100%" height={300}>
              <PieChart>
                <Pie
                  data={trafficDistributionData}
                  cx="50%"
                  cy="50%"
                  labelLine={false}
                  label={({ name, percent }) => `${name}: ${(percent * 100).toFixed(0)}%`}
                  outerRadius={80}
                  fill="#8884d8"
                  dataKey="value"
                >
                  {trafficDistributionData.map((entry, index) => (
                    <Cell key={`cell-${index}`} fill={COLORS[index % COLORS.length]} />
                  ))}
                </Pie>
                <RechartsTooltip />
              </PieChart>
            </ResponsiveContainer>
          </Card>
        </Col>
        <Col xs={24} md={12}>
          <Card title="API请求分布" className="chart-card">
            <ResponsiveContainer width="100%" height={300}>
              <BarChart data={trafficDistributionData}>
                <CartesianGrid strokeDasharray="3 3" />
                <XAxis dataKey="name" />
                <YAxis />
                <RechartsTooltip />
                <Legend />
                <Bar dataKey="value" name="请求数" fill="#8884d8">
                  {trafficDistributionData.map((entry, index) => (
                    <Cell key={`cell-${index}`} fill={COLORS[index % COLORS.length]} />
                  ))}
                </Bar>
              </BarChart>
            </ResponsiveContainer>
          </Card>
        </Col>
      </Row>

      {/* API Monitor Table */}
      <Card title="API监控列表" className="monitor-table-section">
        <div className="table-actions mb-4">
          <Button type="primary" icon={<DownloadOutlined />} onClick={handleExport}>
            导出数据
          </Button>
        </div>
        <Table
          columns={monitorColumns}
          dataSource={apiMonitorList}
          rowKey="id"
          loading={loading}
          pagination={pagination}
          onChange={handlePageChange}
          locale={{
            emptyText: loading ? <Spin /> : <Empty description="暂无监控数据" />,
          }}
        />
      </Card>
    </div>
  );
};

export default MonitorDashboard;